package com.learn.authentication.pojo;

import com.alibaba.fastjson2.annotation.JSONField;
import com.fasterxml.jackson.annotation.JsonIdentityReference;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author DJJ_F
 * @version 1.0
 * @date 2025/04/06
 * @description UserDetails的实现类
 */
@NoArgsConstructor
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class LogUser implements UserDetails {
    private User user;
    private Set<String> permissions;
//    @JSONField(serialize = false)  // 表示不序列化，不存贮他
    @JsonIgnore
    private Set<GrantedAuthority> authorities;

    public LogUser(User user, Set<String> permissions) {
        this.user = user;
        this.permissions = permissions;

    }
    /**
     * 转化的过程不可以写在构造方法
     * 因为可能直接从数据库查询的，而不是new
     * 获取权限信息
     * @return
     */
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        // map表示集合类型的转化，new是构造方法的引用
        if(authorities == null){
            authorities =  permissions.stream()
                            .map(SimpleGrantedAuthority::new)
                            .collect(Collectors.toSet());
        }
        return authorities;
    }

    @Override
    public String getPassword() {
        return user.getPassword();
    }

    @Override
    public String getUsername() {
        return user.getUsername();
    }
}
